MACHINE LEARNING

Universidad Castro Carazo

IIC - 2023
</br>

Este notebook contiene la primer parte del caso de estudio para el curso de Machine Learning desarollado por la estudiante Judith Bustos Siles.

El mismo contiene importación de librerías para EDA con Data Profiling y exportación del archivo en formato .xlsx

</br>

DESCRIPCIÓN DEL CASO

</br>

Esta investigación se centró en el caso de los pagos por defecto de los clientes de Banco Uno y compara la precisión predictiva de la probabilidad de incumplimiento entre seis métodos de minería de datos.

De la perspectiva de la gestión de riesgos, el resultado de la precisión predictiva de la estimación La probabilidad de incumplimiento será más valiosa que el resultado binario de la clasificación de Clientes creíbles o no creíbles.

Debido a que se desconoce la probabilidad real de incumplimiento, este estudio presentó el novedoso método de clasificación de suavizado para estimar la probabilidad real de defecto. Con la probabilidad real de incumplimiento como variable de respuesta (Y), y la probabilidad predictiva de incumplimiento como la variable independiente (X), la simple lineal El resultado de la regresión (Y = A + BX) muestra que el modelo de pronóstico producido por la red neuronal tiene el coeficiente de determinación más alto; su intersección de regresión (A) es cercano a cero y coeficiente de regresión (B) a uno. Por lo tanto, entre los seis datos de minería técnicas, la red neuronal artificial es la única que puede estimar con precisión el valor real probabilidad de incumplimiento.

</br>

CARGAR LIBRERÍAS

Estas primeras líneas de código tienen la funcionalidad de importar todas las librerías necesarias para iniciar con el proceso de EDA/análisis requerido para poder normalizar el set de datos otorgado por Banco Uno.

</br>

In [1]:
import pymysql
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import warnings 
warnings.filterwarnings("ignore")
from ydata_profiling import ProfileReport

CARGAR DATOS

El siguiente código permite la conexión a una base de datos y que a través de una sentencia SQL cargará el set de datos requerido para el análisis solicitado.

In [2]:
connection = pymysql.connect(host ='data-analytics-2018.cbrosir2cswx.us-east-1.rds.amazonaws.com',
user = 'deepAnalytics',
password = 'Sqltask1234!',
database = 'Credit',
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor)
In [3]:
df = pd.read_sql('SELECT * FROM credit', con=connection)
In [4]:
df.head(5)
Out[4]:
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 ... X15 X16 X17 X18 X19 X20 X21 X22 X23 Y
0 LIMIT_BAL SEX EDUCATION MARRIAGE AGE PAY_0 PAY_2 PAY_3 PAY_4 PAY_5 ... BILL_AMT4 BILL_AMT5 BILL_AMT6 PAY_AMT1 PAY_AMT2 PAY_AMT3 PAY_AMT4 PAY_AMT5 PAY_AMT6 default payment next month
1 20000 female university 1 24 2 2 -1 -1 -2 ... 0 0 0 0 689 0 0 0 0 default
2 120000 female university 2 26 -1 2 0 0 0 ... 3272 3455 3261 0 1000 1000 1000 0 2000 default
3 90000 female university 2 34 0 0 0 0 0 ... 14331 14948 15549 1518 1500 1000 1000 1000 5000 not default
4 50000 female university 1 37 0 0 0 0 0 ... 28314 28959 29547 2000 2019 1200 1100 1069 1000 not default

5 rows × 24 columns

Generación del archivo CSV.

In [5]:
df.to_csv('BancoUno.csv',header = False, index = False)

PANDAS PROFILING

Pandas Profiling genera un archivo HTML con una descripcion detallada de cada una de las variables que conforman el set de datos. Este método brinda mayor visualización de cómo deben ser analizadas dichas variables.

In [6]:
credit = df
In [7]:
profile = ProfileReport(credit, title="Profiling Report")
profile
Summarize dataset:   0%|          | 0/5 [00:00<?, ?it/s]
Generate report structure:   0%|          | 0/1 [00:00<?, ?it/s]
Render HTML:   0%|          | 0/1 [00:00<?, ?it/s]
Out[7]:

LIMPIEZA Y TRANSFORMACIÓN

En esta sección se eliminan los datos duplicados del set, posterior de hace ajuste de los encabezados y finalmente se hace la normalización de los datos que requerimos de tipo numérico.

In [8]:
credit.drop_duplicates(subset = None, keep ='first', inplace = True, ignore_index = True)
credit.shape
Out[8]:
(2397, 24)
In [9]:
encabezado = credit.loc[credit['X1'] == 'LIMIT_BAL']
df_list = encabezado.to_numpy().tolist()
print(df_list)
[['LIMIT_BAL', 'SEX', 'EDUCATION', 'MARRIAGE', 'AGE', 'PAY_0', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6', 'BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6', 'default payment next month']]
In [10]:
credit = credit.rename(columns = {'X1':'LIMIT_BAL', 'X2':'SEX', 'X3':'EDUCATION', 'X4':'MARRIAGE',
                                'X5':'AGE', 'X6':'PAY_0', 'X7':'PAY_2', 'X8':'PAY_3', 'X9':'PAY_4',
                                'X10':'PAY_5', 'X11':'PAY_6','X12':'BILL_AMT1', 'X13':'BILL_AMT2',
                                'X14':'BILL_AMT3', 'X15':'BILL_AMT4', 'X16':'BILL_AMT5', 'X17':'BILL_AMT6',
                                'X18':'PAY_AMT1', 'X19':'PAY_AMT2', 'X20':'PAY_AMT3', 'X21':'PAY_AMT4',
                                'X22':'PAY_AMT5', 'X23':'PAY_AMT6', 'default payment next month (Y)':'Y'})

credit.drop([0], axis = 0, inplace = True)
credit.reset_index(inplace = True, drop = False)
credit.head(5)
Out[10]:
index LIMIT_BAL SEX EDUCATION MARRIAGE AGE PAY_0 PAY_2 PAY_3 PAY_4 ... BILL_AMT4 BILL_AMT5 BILL_AMT6 PAY_AMT1 PAY_AMT2 PAY_AMT3 PAY_AMT4 PAY_AMT5 PAY_AMT6 Y
0 1 20000 female university 1 24 2 2 -1 -1 ... 0 0 0 0 689 0 0 0 0 default
1 2 120000 female university 2 26 -1 2 0 0 ... 3272 3455 3261 0 1000 1000 1000 0 2000 default
2 3 90000 female university 2 34 0 0 0 0 ... 14331 14948 15549 1518 1500 1000 1000 1000 5000 not default
3 4 50000 female university 1 37 0 0 0 0 ... 28314 28959 29547 2000 2019 1200 1100 1069 1000 not default
4 5 50000 male university 1 57 -1 0 -1 0 ... 20940 19146 19131 2000 36681 10000 9000 689 679 not default

5 rows × 25 columns

In [11]:
credit.drop(['index'], axis=1,inplace=True)
credit.head(5)
Out[11]:
LIMIT_BAL SEX EDUCATION MARRIAGE AGE PAY_0 PAY_2 PAY_3 PAY_4 PAY_5 ... BILL_AMT4 BILL_AMT5 BILL_AMT6 PAY_AMT1 PAY_AMT2 PAY_AMT3 PAY_AMT4 PAY_AMT5 PAY_AMT6 Y
0 20000 female university 1 24 2 2 -1 -1 -2 ... 0 0 0 0 689 0 0 0 0 default
1 120000 female university 2 26 -1 2 0 0 0 ... 3272 3455 3261 0 1000 1000 1000 0 2000 default
2 90000 female university 2 34 0 0 0 0 0 ... 14331 14948 15549 1518 1500 1000 1000 1000 5000 not default
3 50000 female university 1 37 0 0 0 0 0 ... 28314 28959 29547 2000 2019 1200 1100 1069 1000 not default
4 50000 male university 1 57 -1 0 -1 0 0 ... 20940 19146 19131 2000 36681 10000 9000 689 679 not default

5 rows × 24 columns

In [12]:
credit.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2396 entries, 0 to 2395
Data columns (total 24 columns):
 #   Column     Non-Null Count  Dtype 
---  ------     --------------  ----- 
 0   LIMIT_BAL  2396 non-null   object
 1   SEX        2396 non-null   object
 2   EDUCATION  2396 non-null   object
 3   MARRIAGE   2396 non-null   object
 4   AGE        2396 non-null   object
 5   PAY_0      2396 non-null   object
 6   PAY_2      2396 non-null   object
 7   PAY_3      2396 non-null   object
 8   PAY_4      2396 non-null   object
 9   PAY_5      2396 non-null   object
 10  PAY_6      2396 non-null   object
 11  BILL_AMT1  2396 non-null   object
 12  BILL_AMT2  2396 non-null   object
 13  BILL_AMT3  2396 non-null   object
 14  BILL_AMT4  2396 non-null   object
 15  BILL_AMT5  2396 non-null   object
 16  BILL_AMT6  2396 non-null   object
 17  PAY_AMT1   2396 non-null   object
 18  PAY_AMT2   2396 non-null   object
 19  PAY_AMT3   2396 non-null   object
 20  PAY_AMT4   2396 non-null   object
 21  PAY_AMT5   2396 non-null   object
 22  PAY_AMT6   2396 non-null   object
 23  Y          2396 non-null   object
dtypes: object(24)
memory usage: 449.4+ KB
In [13]:
credit[['LIMIT_BAL', 'AGE', 'PAY_0', 'PAY_2', 'PAY_3', 
        'PAY_4', 'PAY_5', 'PAY_6', 'BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 
        'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 
        'PAY_AMT5', 'PAY_AMT6']] = credit[['LIMIT_BAL', 'AGE', 'PAY_0', 'PAY_2', 'PAY_3', 
        'PAY_4', 'PAY_5', 'PAY_6', 'BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 
        'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 
        'PAY_AMT5', 'PAY_AMT6']].astype("int")
In [14]:
credit.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2396 entries, 0 to 2395
Data columns (total 24 columns):
 #   Column     Non-Null Count  Dtype 
---  ------     --------------  ----- 
 0   LIMIT_BAL  2396 non-null   int32 
 1   SEX        2396 non-null   object
 2   EDUCATION  2396 non-null   object
 3   MARRIAGE   2396 non-null   object
 4   AGE        2396 non-null   int32 
 5   PAY_0      2396 non-null   int32 
 6   PAY_2      2396 non-null   int32 
 7   PAY_3      2396 non-null   int32 
 8   PAY_4      2396 non-null   int32 
 9   PAY_5      2396 non-null   int32 
 10  PAY_6      2396 non-null   int32 
 11  BILL_AMT1  2396 non-null   int32 
 12  BILL_AMT2  2396 non-null   int32 
 13  BILL_AMT3  2396 non-null   int32 
 14  BILL_AMT4  2396 non-null   int32 
 15  BILL_AMT5  2396 non-null   int32 
 16  BILL_AMT6  2396 non-null   int32 
 17  PAY_AMT1   2396 non-null   int32 
 18  PAY_AMT2   2396 non-null   int32 
 19  PAY_AMT3   2396 non-null   int32 
 20  PAY_AMT4   2396 non-null   int32 
 21  PAY_AMT5   2396 non-null   int32 
 22  PAY_AMT6   2396 non-null   int32 
 23  Y          2396 non-null   object
dtypes: int32(20), object(4)
memory usage: 262.2+ KB
In [15]:
credit.head(3)
Out[15]:
LIMIT_BAL SEX EDUCATION MARRIAGE AGE PAY_0 PAY_2 PAY_3 PAY_4 PAY_5 ... BILL_AMT4 BILL_AMT5 BILL_AMT6 PAY_AMT1 PAY_AMT2 PAY_AMT3 PAY_AMT4 PAY_AMT5 PAY_AMT6 Y
0 20000 female university 1 24 2 2 -1 -1 -2 ... 0 0 0 0 689 0 0 0 0 default
1 120000 female university 2 26 -1 2 0 0 0 ... 3272 3455 3261 0 1000 1000 1000 0 2000 default
2 90000 female university 2 34 0 0 0 0 0 ... 14331 14948 15549 1518 1500 1000 1000 1000 5000 not default

3 rows × 24 columns

EXPORTACIÓN

Exportación del archivo CSV para futuro análisis.

In [17]:
credit.to_excel("credit.xlsx")
In [ ]: